import { login, logout, getInfo } from '../../api/User/admin'
import { encrypt, decrypt } from '../../utils/encryption'

const user = {
  state: {
    token: localStorage.getItem("token"),
    username: localStorage.getItem("username"),
    avatar: localStorage.getItem("avatar"),
    roles: ""
  },
    mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      localStorage.setItem("token",token)
    },
    SET_USERNAME: (state, username) => {
      state.username = username
      localStorage.setItem("username",username)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      // localStorage.setItem("roles",roles)
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(encrypt(JSON.stringify(userInfo))).then(response => {
          const data = response.data
          commit('SET_TOKEN', data.token)
          commit('SET_USERNAME', data.username)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', "")
        commit('SET_USERNAME', "")
         // localStorage.removeItem("roles")
        resolve()
      //   logout(state.token).then(() => {
         
      //   }).catch(error => {
      //     reject(error)
      //   })
       })
    }
  }
}

export default user
